package zdar.entities;

import java.util.Arrays;
import java.util.Random;

/**
 * This class allows for Dice objects to be created. 
 * The purpose is to simplify the dice rolling process, 
 * instead of tracking 3 numbers and calculating them correctly, you just need to keep track of one object.
 * This should be used attributes, skills, damage, etc.
 * Each dice object should roll itself and return the integer result.
 * @author danbye50
 *
 */
public class Dice {
	private int diceCount, diceType, modifier;
	private boolean wildcard;	
	
	// TODO implement some kind of RapidFireDice class which extends this one. RoF > 1 weapons need a special roll() method.
	
	public Dice(){
		this(6);
	}
	public Dice(int diceType){
		this (1, diceType);
	}
	public Dice(int diceCount, int diceType){
		this(diceCount, diceType, 0);
	}
	public Dice(int diceCount, int diceType, int modifier){
		this(diceCount, diceType, modifier, false);
	}
	public Dice(int diceCount, int diceType, int modifier, boolean wildcard){
		this.wildcard = wildcard;
		this.diceCount = diceCount;
		this.diceType = diceType;
		this.modifier = modifier;
	}
	
	public int roll(){
		Random r = new Random();
		int amount = 0;
		int roll = 0;
		
		// Normal Roll
		if(!wildcard){
			for (int i=0; i<diceCount; i++){
				roll = r.nextInt(diceType) + 1;
				System.out.println("    Roll " + (i + 1) + ": " + roll); //DEBUG
				amount += roll;
			}
			
		// Wildcard roll
		}else{
			int wildRoll = r.nextInt(6) + 1;		
			
			if (diceCount == 1){
				roll = r.nextInt(diceType) + 1;
				if (wildRoll > roll){
					amount = wildRoll;
					System.out.println("Wild (" + wildRoll + " vs " + roll + ")");      //DEBUG
				}else{
					amount = roll;
				}
				
			}else{			
				int[] rolls = new int[diceCount];
				for (int i=0; i<diceCount; i++){
					rolls[i] = r.nextInt(diceType) + 1;
					System.out.println("Roll " + (i + 1) + ": " + rolls[i]);    //DEBUG
				}
				Arrays.sort(rolls);		
				
				// re-roll lowest w/ d6
				if (wildRoll > rolls[0]){	
					System.out.println("Wild (" + wildRoll + " vs " + rolls[0] + ")");  //DEBUG
					rolls[0] = wildRoll;
				}
				
				// Calculate final amount
				for (int i=0; i<diceCount; i++){
					amount += rolls[i];
				}
			}
		}
		
		return amount + modifier;
	}
	
	public int totalValue(){
		return (diceCount * diceType) + modifier;
	}
	
	// This is a convenience method when a one off roll is required (i.e. extra die roll when scoring a Raise)
	public static int roll(int die){
		Random r = new Random();
		return r.nextInt(die) + 1;
	}
	
}
